package bsc.war.form;



import bsc.ejb.entity.ColorimetrySettings;
import bsc.ejb.entity.Label;
import bsc.ejb.entity.Milestone;
import bsc.ejb.entity.MilestoneTracer;
import bsc.ejb.entity.Person;
import bsc.ejb.entity.PersonScoreCard;
import bsc.ejb.entity.Project;
import bsc.ejb.entity.Settings;
import bsc.ejb.entity.Task;
import bsc.ejb.entity.Tracer;
import bsc.ejb.metadata.Colorimetry;
import bsc.ejb.metadata.Framework;
import bsc.war.delegate.DelegateBSC;
import bsc.war.factory.Factory;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

/**
 *
 * @author memozac
 */
public class NewProject extends AbstractController  {

     @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
         HttpServletResponse response) throws Exception {

        try {
            DelegateBSC delegate = (DelegateBSC) Factory.getBean("DelegateBSC");

            Project project = (Project) Factory.getBean("Project");
            Settings projectSettings = (Settings) Factory.getBean("Settings");

            if( request.getParameter("existingProjectId") != null && NumberUtils.isNumber(request.getParameter("existingProjectId")) )
            {
                project = delegate.findProject(Long.parseLong(request.getParameter("existingProjectId")));
                projectSettings = project.getSettings();
            }
            //ScoreCardRelation scoreCardRelation = (ScoreCardRelation) Factory.getBean("ScoreCardRelation");

            //Long idScoreCard = request.getParameter("scoreCard") != null && NumberUtils.isNumber(request.getParameter("scoreCard")) ? Long.parseLong(request.getParameter("scoreCard")) : null;
            Long idPerson = request.getParameter("person") != null && NumberUtils.isNumber(request.getParameter("person")) ? Long.parseLong(request.getParameter("person")) : null;
            //ScoreCard scoreCard = delegate.findScoreCard(idScoreCard);

            //project
            project.setDescription(request.getParameter("description"));
            project.setName(request.getParameter("name"));
            Person person = delegate.findPerson(idPerson);
            project.setResponsible(person);

            if( request.getParameter("existingProjectId") == null )
                delegate.createProject(project);
            else
                delegate.updateProject(project);

            //personScoreCard
            /*PersonScoreCard personScoreCard = (PersonScoreCard) Factory.getBean("PersonScoreCard");

            personScoreCard.setPerson(person);
            personScoreCard.setScoreCard(project);
            delegate.createPersonScoreCard(personScoreCard);*/

            //project settings
            projectSettings.setScoreCard(project);
            projectSettings.setType(Settings.Type.SCORECARD);
            //scoreCard.setUnit("(%)");

            if( request.getParameter("existingProjectId") == null )
                delegate.createSettings(projectSettings);
            else
                delegate.updateSettings(projectSettings);

            project.setSettings(projectSettings);
            delegate.updateProject(project);

            //scoreCardRelation
            /*
            scoreCardRelation.setScoreCard(scoreCard);
            scoreCardRelation.setOtherScoreCard(project);
            delegate.createScoreCardRelation(scoreCardRelation);*/

            //colorimetries

            Framework framework = delegate.findFramework(Boolean.TRUE);
            List<Colorimetry> colorimetries = delegate.findColorimetry(framework, Boolean.TRUE);

            if( request.getParameter("existingProjectId") == null ) {
                List<ColorimetrySettings> css = delegate.findColorimetrySettings(project);
                for(ColorimetrySettings cs : css)
                    delegate.deleteColorimetrySettings(cs);
            }

            for (Colorimetry colorimetry : colorimetries) {
                ColorimetrySettings colorimetrySettings = request.getParameter("existingProjectId") != null ? delegate.findColorimetrySettings(colorimetry,projectSettings) : (ColorimetrySettings) Factory.getBean("ColorimetrySettings");
                String minValue = request.getParameter("min_value_colorimetry_" + colorimetry.getIdColorimetry());
                String maxValue = request.getParameter("max_value_colorimetry_" + colorimetry.getIdColorimetry());
                colorimetrySettings.setMaxScore((NumberUtils.isNumber(maxValue) ? Double.parseDouble(maxValue) : Double.valueOf(maxValue))/100);
                colorimetrySettings.setMinScore((NumberUtils.isNumber(minValue) ? Double.parseDouble(minValue) : Double.valueOf(minValue))/100);
                colorimetrySettings.setSettings(projectSettings);
                colorimetrySettings.setColorimetry(colorimetry);
                if(request.getParameter("existingProjectId") != null) delegate.updateColorimetrySettings(colorimetrySettings);
                else delegate.createColorimetrySettings(colorimetrySettings);
            }


            //tracers
            Tracer budgetTracer = null, progressTracer = null;
            if( request.getParameter("existingProjectId") == null ) {
                budgetTracer = (Tracer) Factory.getBean("Tracer");
                budgetTracer.setType(Tracer.Type.BUDGET);
                budgetTracer.setName("Presupuesto "+project.getName());
                budgetTracer.setPercentFactor(Double.parseDouble(request.getParameter("budgetPercentFactor")));
                budgetTracer.setProject(project);
                delegate.createTracer(budgetTracer);

                progressTracer = (Tracer) Factory.getBean("Tracer");
                progressTracer.setType(Tracer.Type.PROGRESS);
                progressTracer.setName("Avance "+project.getName());
                progressTracer.setPercentFactor(Double.parseDouble(request.getParameter("progressPercentFactor")));
                progressTracer.setProject(project);
                delegate.createTracer(progressTracer);
            } else {
                budgetTracer = delegate.findTracer(project, Tracer.Type.BUDGET);
                progressTracer = delegate.findTracer(project, Tracer.Type.PROGRESS);

                //budgetTracer.setName(request.getParameter("budgetName"));
                budgetTracer.setPercentFactor(Double.parseDouble(request.getParameter("budgetPercentFactor")));
                //progressTracer.setName(request.getParameter("progressName"));
                progressTracer.setPercentFactor(Double.parseDouble(request.getParameter("progressPercentFactor")));

                delegate.updateTracer(budgetTracer);
                delegate.updateTracer(progressTracer);
            }

            // tasks
            DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
            if( request.getParameter("existingProjectId") != null ) {
                List<Task> tasks = delegate.findTask(project);
                for(Task task : tasks) {
                    String newName = request.getParameter("updateTaskName-"+task.getIdTask());
                    if(newName == null)continue;

                    task.setName(newName);
                    if(task instanceof Milestone){
                        ((Milestone)task).setBeginDate(df.parse(request.getParameter("updateBeginDate-" + task.getIdTask())));
                        ((Milestone)task).setEndDate(df.parse(request.getParameter("updateEndDate-" + task.getIdTask())));
                        delegate.updateMilestone((Milestone)task);
                    }
                    else delegate.updateLabel((Label)task);
                }
            } else {
                Label rootTask = (Label)Factory.getBean("Label");
                rootTask.setName(request.getParameter("rootTaskName"));
                rootTask.setProject(project);
                rootTask.setRoot(Boolean.TRUE);
                delegate.createLabel(rootTask);

                HashMap<String, Task> tasks = new HashMap<String, Task>();
                String[] taks = request.getParameterValues("newTask");


                if( taks != null && taks.length > 0 ) for(String taskID : taks) {
                    if(taskID.length() < 1) continue;

                    Task task = (Task)Factory.getBean(request.getParameter("type-"+taskID));
                    task.setProject(project);
                    task.setName(request.getParameter("newTaskName-"+taskID));
                    task.setTask(taskID.indexOf("-") == taskID.lastIndexOf("-") ? rootTask : tasks.get( taskID.substring(0,taskID.lastIndexOf("-")) ));
                    if(task instanceof Milestone){
                        Milestone milestone = (Milestone)task;
                        milestone.setBeginDate(df.parse(request.getParameter("newTaskInitDate-" + taskID)));
                        milestone.setEndDate(df.parse(request.getParameter("newTaskEndDate-" + taskID)));
                        delegate.createMilestone(milestone);

                        MilestoneTracer milestoneBudgetTracer = (MilestoneTracer)Factory.getBean("MilestoneTracer");
                        milestoneBudgetTracer.setMilestone(milestone);
                        milestoneBudgetTracer.setTracer(budgetTracer);
                        delegate.createMilestoneTracer(milestoneBudgetTracer);

                        MilestoneTracer milestoneProgressTracer = (MilestoneTracer)Factory.getBean("MilestoneTracer");
                        milestoneProgressTracer.setMilestone(milestone);
                        milestoneProgressTracer.setTracer(progressTracer);
                        delegate.createMilestoneTracer(milestoneProgressTracer);

                    } else delegate.createLabel((Label)task);

                    tasks.put(taskID, task);
                }
            }

        } catch (Exception e) {
            System.err.println(e);
            e.printStackTrace();
        }

         return new ModelAndView("newProject");
    }

}
